package com.my.vertx.http;

import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerResponse;

/**
 * Vertx 创建http server测试
 * <p><a href="https://vertx.io/docs/vertx-core/java/#_creating_an_http_server">参考 Vertx - Creating an HTTP Server<a/></p>
 *
 * @author: marshal
 * @date: 2023-04-12 13:47
 */
public class VertxHttpServerTest {
    public static void main(String[] args) {
        // 创建vertx对象
        Vertx vertx = Vertx.vertx();
        // 创建HttpServerOptions
        HttpServerOptions options = new HttpServerOptions()
                .setPort(9600)
                .setHost("127.0.0.1")
                .setLogActivity(true);
        // 创建HttpServer
        HttpServer httpServer = vertx.createHttpServer(options);
        // 处理客户端的请求数据
        httpServer.requestHandler(request -> {
            // 获取请求头
            MultiMap headers = request.headers();
            System.out.println("=========================request headers======================");
            System.out.println(headers);
            // 获取请求uri
            String uri = request.uri();
            System.out.println("=========================request uri======================");
            System.out.println(uri);
            // 获取请求参数
            System.out.println("=========================request param======================");
            String name = request.getParam("name");
            System.out.println(name);
            // 设置响应
            HttpServerResponse response = request.response();
            response.end("This is server's response", "UTF-8");
        });
        // 开始监听(这一步一定是要放在requestHandler之后，否则会报错)
        httpServer
                .listen()
                .onComplete(res -> {
                    if (res.succeeded()) {
                        System.out.println("Server is now listening!");
                    } else {
                        System.out.println("Failed to bind!");
                    }
                });

    }
}
